package com.jinzhi.jzweb.service.impl;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzweb.domain.BookConfigDO;
import com.jinzhi.jzweb.domain.ProductTypeDO;
import com.jinzhi.jzweb.pojo.SpecJsonVo;
import com.jinzhi.jzweb.service.BookConfigService;
import com.jinzhi.jzweb.service.ProductTypeService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.OrderSpecsDao;
import com.jinzhi.jzweb.domain.OrderSpecsDO;
import com.jinzhi.jzweb.service.OrderSpecsService;
import com.jinzhi.common.base.CoreServiceImpl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 
 * <pre>
 * 订单规格配置表
 * </pre>
 * <small> 2024-09-18 16:30:13 | lance</small>
 */
@Service
public class OrderSpecsServiceImpl extends CoreServiceImpl<OrderSpecsDao, OrderSpecsDO> implements OrderSpecsService {

    private final ProductTypeService productTypeService;

    private final BookConfigService bookConfigService;

    private final UserService userService;
    public OrderSpecsServiceImpl(ProductTypeService productTypeService,BookConfigService bookConfigService,UserService userService){
        this.productTypeService = productTypeService;
        this.bookConfigService = bookConfigService;
        this.userService = userService;
    }

    /**
     * 订单规格配置分页列表
     * @param orderSpecsDO
     * @return
     */
    @Override
    public Page<OrderSpecsDO> orderSpecList(OrderSpecsDO orderSpecsDO) {
        Page<OrderSpecsDO> pageList = this.selectPage(
                new Page<OrderSpecsDO>(orderSpecsDO.getCurrent(), orderSpecsDO.getSize()),
                new EntityWrapper<OrderSpecsDO>()
                        .eq(null != orderSpecsDO.getCategory(), "category", orderSpecsDO.getCategory())
                        .eq(null != orderSpecsDO.getYear(), "year", orderSpecsDO.getYear())
                        .eq(null != orderSpecsDO.getOrderType(), "order_type", orderSpecsDO.getOrderType())
                        .like(null != orderSpecsDO.getUnitName(),"unit_name",orderSpecsDO.getUnitName())
                        .like(null != orderSpecsDO.getOrderNumber(),"order_number",orderSpecsDO.getOrderNumber())
                        .in((null!=orderSpecsDO.getIdList()&&!orderSpecsDO.getIdList().isEmpty()),"id",orderSpecsDO.getIdList())
                        .orderBy("id", false)
        );
        if(!pageList.getRecords().isEmpty() && pageList.getRecords().size()>0){
            pageList.getRecords().forEach(record->{
                //查询商品类型
                ProductTypeDO productTypeDO = productTypeService.selectById(record.getTypeId());
                if(null!=productTypeDO){
                    record.setTypeName(productTypeDO.getTypeName());
                }
                //获取创建人
                UserDO userDO = userService.selectById(record.getCreaterId());
                if(null!=userDO){
                    record.setCreaterName(userDO.getName()!=null?userDO.getName():userDO.getUsername());
                }
                //处理商品规格 json 获取其中的金额，用/分割
                JSONArray array = JSON.parseArray(record.getSpecs());
                if(!array.isEmpty() && array.size()>0){
                    List<String> moneyList = new LinkedList<>();
                    List<String> specList = new LinkedList<>();
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        String money = jsonObject.getString("money");
                        String spec = jsonObject.getString("spec");
                        BookConfigDO bookConfigDO = bookConfigService.selectById(spec);
                        if(null!=bookConfigDO){
                            specList.add(bookConfigDO.getBookName());
                        }
                        moneyList.add(money);
                    }
                    record.setMoney(String.join("/",moneyList));
                    record.setBookName(String.join("/",specList));
                }

            });
        }
        return pageList;
    }

    /**
     * 新增规格配置
     * @param orderSpecsDO
     */
    @Override
    public void saveSpec(OrderSpecsDO orderSpecsDO) {
        getSpecJson(orderSpecsDO);
        //年份
        SimpleDateFormat sf = new SimpleDateFormat("yyyy");
        orderSpecsDO.setYear(Integer.valueOf(sf.format(new Date())));
        this.insert(orderSpecsDO);
        //拿id当编号
        String orderNum = getOrderNum(orderSpecsDO.getId());
        OrderSpecsDO orderSpecsDO1 = new OrderSpecsDO();
        orderSpecsDO1.setId(orderSpecsDO.getId());
        orderSpecsDO1.setOrderNumber(orderNum);
        this.updateById(orderSpecsDO1);
    }


    /**
     * 编辑规格配置
     * @param orderSpecsDO
     */
    @Override
    public void editSpec(OrderSpecsDO orderSpecsDO) {
        Assert.notNull(orderSpecsDO.getId(),"参数'id'不能为空");
        getSpecJson(orderSpecsDO);
        this.updateById(orderSpecsDO);
    }

    /**
     * 导出
     * @param orderSpecsDO
     * @return
     */
    @Override
    public List<OrderSpecsDO> exportOrderList(OrderSpecsDO orderSpecsDO) {
        List<OrderSpecsDO> specsDOList = new LinkedList<>();//存储导出信息
        Page<OrderSpecsDO> page = this.orderSpecList(orderSpecsDO);
        if(!page.getRecords().isEmpty()){
            page.getRecords().forEach(record->{
                //处理书籍规格 每种规格是一条数据
                JSONArray array = JSON.parseArray(record.getSpecs());
                if(!array.isEmpty() && array.size()>0){
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        SpecJsonVo specJsonVo = new SpecJsonVo();
                        String spec = jsonObject.getString("spec");
                        BookConfigDO bookConfigDO = bookConfigService.selectById(spec);
                        if(null!=bookConfigDO){
                            specJsonVo.setPrice(bookConfigDO.getPrice().toString());
                            specJsonVo.setSpec(bookConfigDO.getBookName());
                        }
                        specJsonVo.setMoney(jsonObject.getString("money"));
                        specJsonVo.setDiscount(jsonObject.getString("discount"));
                        specJsonVo.setNumber(jsonObject.getString("number"));

                        OrderSpecsDO orderSpecsDO1 = new OrderSpecsDO();
                        BeanUtils.copyProperties(record,orderSpecsDO1);
                        orderSpecsDO1.setSpecJsonVo(specJsonVo);
                        specsDOList.add(orderSpecsDO1);
                    }
                }
            });
        }
        return specsDOList;
    }

    private void getSpecJson(OrderSpecsDO orderSpecsDO) {
        //处理年份时间
        if(StringUtil.isNull(orderSpecsDO.getSpecs())){
            return;
        }
        JSONArray array = JSON.parseArray(orderSpecsDO.getSpecs());
        if(!array.isEmpty() && array.size()>0){
            BigDecimal totalAmount = new BigDecimal(0);
            for (int i = 0; i < array.size(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                String spec = jsonObject.getString("spec");
                String number = jsonObject.getString("number");
                String discount = jsonObject.getString("discount");
                BigDecimal money = new BigDecimal(0);
                //通过书籍id查询书籍单价
                BookConfigDO bookConfigDO = bookConfigService.selectById(spec);
                //单价和数量不能等于0 否则总价就是0
                if(null!=bookConfigDO && bookConfigDO.getPrice().compareTo(new BigDecimal(0)) == 1 && !number.equals("0")){
                    //计算价格：单价 * 数量 * 折扣
                    money = bookConfigDO.getPrice().multiply(new BigDecimal(number)).multiply(new BigDecimal(discount)).setScale(2, BigDecimal.ROUND_HALF_UP);
                }
                jsonObject.put("money",money);
                totalAmount = totalAmount.add(money);
            }
            String specs = array.toString();
            orderSpecsDO.setSpecs(specs);
            orderSpecsDO.setTotalAmount(totalAmount);
        }
    }


    public String getOrderNum(Long id){
        SimpleDateFormat sf = new SimpleDateFormat("YYYYMMdd");
        Date date = new Date();
        String format = sf.format(date);

        String idStr = id.toString();
        //默认id六位，不足的用0补充
        switch (id.toString().length()){
            case 1:idStr = "00000"+id;break;
            case 2:idStr = "0000"+id;break;
            case 3:idStr = "000"+id;break;
            case 4:idStr = "00"+id;break;
            case 5:idStr = "0"+id;break;
            default:idStr = id.toString();
        }

        //默认订单编号格式：YYYYMMdd + id
        return format + idStr;
    }

}
